﻿using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Models.Dto;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace DataManageSystem.Services
{
    public class OfficeDevCategoryServices
    {
        private readonly ApplicationDbContext _context;

        public OfficeDevCategoryServices(ApplicationDbContext context)
        {
            _context = context;
        }

        public Result selectCateGoryData(int pageNum, int pageSize, string categoryName)
        {
            var query = _context.OfficeDevCategories.AsQueryable();
            if (!string.IsNullOrEmpty(categoryName))
            {
                query = query.Where(u => u.CategoryName.Contains(categoryName));
            }

            int total = query.Count(); // 获取总记录数

            var categories = query
                .OrderByDescending(u => u.Id)
                .Skip((pageNum - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return Result.Success(categories, total);
        }

        public void add(OfficeDevCategory officeDevCategory)
        {
            _context.OfficeDevCategories.Add(officeDevCategory);
            _context.SaveChanges();
        }

        public void Update(OfficeDevCategory devCategory)
        {
            var existOfficeDevice = _context.OfficeDevCategories.FirstOrDefault(m =>
                m.Id == devCategory.Id
            );
            existOfficeDevice.CategoryName = devCategory.CategoryName;
            _context.OfficeDevCategories.Update(existOfficeDevice);
            _context.SaveChanges();
        }

        public void Delete(int id)
        {
            var officeDevCategory = _context.OfficeDevCategories.FirstOrDefault(m => m.Id == id);
            if (officeDevCategory != null)
            {
                _context.OfficeDevCategories.Remove(officeDevCategory);
                _context.SaveChanges();
            }
            else
            {
                throw new ServiceException("数据不存在");
            }
        }

        public object getAllCategories()
        {
            return _context
                .OfficeDevCategories.Select(c => new
                {
                    label = c.CategoryName,
                    value = c.CategoryName,
                })
                .ToList();
        }
    }
}
